package cn.itcast.bos.web.action.base;


import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.CourierService;
import cn.itcast.bos.utils.FileUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
import org.apache.commons.lang.StringUtils;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Role;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.*;

/**
 * Created by xbqco on 2018/7/12.
 */
@Controller
public class CourierController {

    @Autowired
    private CourierService courierService;

    @RequestMapping("courier_save")

    public String save(Courier courier){
        courierService.save(courier);
        return "redirect:/pages/base/courier.html";
    }

    @RequestMapping("courier_pageQuery")

    @ResponseBody
    public Map<String ,Object> findAll(int page,int rows,Courier model){

        Specification<Courier> spec= getSpec(model);
        PageRequest pageRequest = new PageRequest(page-1,rows);
        Page<Courier> p = courierService.findPageData(spec,pageRequest);
        Map<String ,Object> map = new HashMap<>();
        System.out.println("查询到的数量:"+p.getTotalElements());
        map.put("total",p.getTotalElements());
        map.put("rows",p.getContent());
        return  map;

    }



    public Specification<Courier> getSpec(Courier model){
        Specification<Courier> spec = new Specification<Courier>() {
            @Override
            public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if(StringUtils.isNotBlank(model.getCourierNum())){
                    System.out.println("走了工号查询"+model.getCourierNum());
                    Predicate p1 = cb.equal(root.get("courierNum").as(String.class),model.getCourierNum());
                    list.add(p1);
                }
               if(model.getStandard() != null && StringUtils.isNotBlank(model.getStandard().getName()) ){


                    Join<Courier,Standard> join = root.join("standard",JoinType.INNER);
                        System.out.println("走了标准查询");
                        Predicate p2 = cb.like(join.get("name").as(String.class),"%"+model.getStandard().getName()+"%");
                        list.add(p2);
                    }

                if(StringUtils.isNotBlank(model.getCompany())){
                    System.out.println("走了公司查询"+model.getCompany());
                    Predicate p3 = cb.like(root.get("company").as(String.class),"%"+model.getCompany()+"%");
                    list.add(p3);
                }

                if(StringUtils.isNotBlank(model.getType())){
                    System.out.println("走了type查询"+model.getType());
                    Predicate p4 = cb.equal(root.get("type").as(String.class),model.getType());
                    list.add(p4);
                }
                Predicate[] ll = list.toArray(new Predicate[0]);
                Predicate pp= cb.and(ll);
                return pp;
            }
        };
    return spec;
    }

    @RequestMapping("courier_findAll")
    @ResponseBody
    public List<Courier> find(){
        return courierService.findAll();
    }

    @RequestMapping("courier_delete")
    public String delete(String ids){
        if(ids.contains(",")){
            System.out.println(ids);
            String[] ids1= ids.split(",");
            for(int i=0;i<ids1.length;i++){
                courierService.updateDeltag(Integer.parseInt(ids1[1]));
            }
        }else{
            courierService.updateDeltag(Integer.parseInt(ids));
            System.out.println(ids);
        }

        return "redirect:/pages/base/courier.html";
    }

    @RequestMapping("courier_restore")
    public String restore(String ids){
        if(ids.contains(",")){
            System.out.println(ids);
            String[] ids1= ids.split(",");
            for(int i=0;i<ids1.length;i++){
                courierService.updateDeltag(Integer.parseInt(ids1[1]));
            }
        }else{
            courierService.restore(Integer.parseInt(ids));
            System.out.println(ids);
        }

        return "redirect:/pages/base/courier.html";
    }

    //查找关联到某一定区的快递员
    @RequestMapping("fixedArea_findCourier")
    public Page<Courier> findCourierByFixedArea(String fixedAreaId,int page,int rows){
        Pageable pageable = new PageRequest(page-1,rows);

       return null;

    }

    @RequestMapping("courier_saveAsPdf")
    public void saveAsPdf(Courier courier, HttpServletResponse response, HttpServletRequest request) throws Exception {

        Specification<Courier> spec= getSpec(courier);
        List<Courier> list = courierService.findBySpec(spec);
        response.setContentType("application/pdf");
        String name = "快递员.pdf";
        String agent = request.getHeader("user-agent");
        name = FileUtils.encodeDownloadFilename(name, agent);
        response.setHeader("Content-Disposition","attachment;filename="+name);
        String courierJasper = request.getSession().getServletContext().getRealPath("WEB-INF/jasper/report3.jrxml");
        JasperReport report = JasperCompileManager.compileReport(courierJasper);
        Map<String,Object> map= new HashMap();
        map.put("company","联邦快递");
        map.put("standard",courier.getStandard().getName());
        map.put("type",courier.getType());

        JasperPrint jasperPrint = JasperFillManager.fillReport(report,map,new JRBeanCollectionDataSource(list));
        JRPdfExporter exporter = new JRPdfExporter();
        exporter.setParameter(JRPdfExporterParameter.JASPER_PRINT,jasperPrint);
        exporter.setParameter(JRPdfExporterParameter.OUTPUT_STREAM,response.getOutputStream());
        exporter.exportReport();
        response.getOutputStream().close();
    }

    @RequestMapping("courier_doCharts")
    @ResponseBody
    public Map doCharts(){
        List<Object[]> list = courierService.findCourierGroupByCompany();
        List ca = new ArrayList();
        List su =new ArrayList();
        for(Object[] objects:list){
            ca.add((String)objects[0]);
            su.add((long)objects[1]);
        }
        System.out.println("***********************"+list.size());
        Map map = new HashMap();
        map.put("categories",ca);
        map.put("series",su);
        return map;
    }


}
